
 /**
 * RequestUtils.java.java.
 * User: BrianChen Date: 2012-7-29 下午01:27:42
 *
 * Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
 * All rights reserved.
 */
package com.collapsar.core.util.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <pre>
 * REVISIONS: 
 * Version 	Date 		Author 			Description
 * ------------------------------------------------------------------- 
 * 1.0 		2012-7-29 	BrianChen 	1. Created this class. 
 * </pre>
 * 
 * @author BrianChen
 * @date 2012-7-29 下午01:27:42
 * @version 1.0
 * @see
 * 
 */
public class RequestUtils {
	private static final Logger logger = LoggerFactory.getLogger(RequestUtils.class);
	
	
	/**
	 * 获取指定名称的Http请求参数值
	 * @param request web请求
	 * @param name 数名称
	 * @return
	 */
	public static String getQueryParam(HttpServletRequest request, String name) {
		if (StringUtils.isBlank(name)) {
			return null;
		}
				
		String values[] = (String[])getQueryParams(request).get(name);
		if (values != null && values.length > 0) {
			return values[values.length - 1];
		} else {
			return null;
		}
	}
	
	/**
	 * 获取Http请求的参数列表
	 * 如果是get方式提交的数据，使用URLDecoder以UTF-8格式转码。
	 * 如果请求是以post方法提交的，那么将通过HttpServletRequest.getParameterMap获取。
	 * @param request
	 * @return
	 */
	public static Map<String, Object> getQueryParams(HttpServletRequest request) {
		Map<String, String[]> map = null;
		if (request.getMethod().equalsIgnoreCase(WebConstants.POST)) {
			map = request.getParameterMap();
		} else {
			String queryStr = request.getQueryString();
			if (StringUtils.isBlank(queryStr)) {
				return new HashMap<String, Object>();
			}
			try {
				queryStr = URLDecoder.decode(queryStr, WebConstants.UTF8);
			} catch (UnsupportedEncodingException e) {
				logger.error("encoding " + WebConstants.UTF8 + " not support?", e);
			}
			map = parseQueryString(queryStr);
		}

		Map<String, Object> params = new HashMap<String, Object>(map.size());
		int len = 0;
		for (Map.Entry<String, String[]> entry : map.entrySet()) {
			len = entry.getValue().length;
			if (len == 1) {
				params.put(entry.getKey(), entry.getValue()[0]);
			} else if (len > 1) {
				params.put(entry.getKey(), entry.getValue());
			}
		}
		return params;
	}
	
	/**
	 * 
	 * Parses a query string passed from the client to the server and builds a
	 * <code>HashTable</code> object with key-value pairs. The query string
	 * should be in the form of a string packaged by the GET or POST method,
	 * that is, it should have key-value pairs in the form <i>key=value</i>,
	 * with each pair separated from the next by a &amp; character.
	 * 
	 * <p>
	 * A key can appear more than once in the query string with different
	 * values. However, the key appears only once in the hashtable, with its
	 * value being an array of strings containing the multiple values sent by
	 * the query string.
	 * 
	 * <p>
	 * The keys and values in the hashtable are stored in their decoded form, so
	 * any + characters are converted to spaces, and characters sent in
	 * hexadecimal notation (like <i>%xx</i>) are converted to ASCII characters.
	 * 
	 * @param queryStr
	 *            a string containing the query to be parsed
	 * 
	 * @return a <code>HashTable</code> object built from the parsed key-value
	 *         pairs
	 * 
	 * @exception IllegalArgumentException
	 *                if the query string is invalid
	 * 
	 */
	public static Map<String, String[]> parseQueryString(String queryStr) {
		String valArray[] = null;
		if (queryStr == null) {
			throw new IllegalArgumentException();
		}
		Map<String, String[]> ht = new HashMap<String, String[]>();
		StringTokenizer st = new StringTokenizer(queryStr, "&");
		while (st.hasMoreTokens()) {
			String pair = (String) st.nextToken();
			int pos = pair.indexOf('=');
			if (pos == -1) {
				continue;
			}
			String key = pair.substring(0, pos);
			String val = pair.substring(pos + 1, pair.length());
			if (ht.containsKey(key)) {
				String oldVals[] = (String[]) ht.get(key);
				valArray = new String[oldVals.length + 1];
				for (int i = 0; i < oldVals.length; i++) {
					valArray[i] = oldVals[i];
				}
				valArray[oldVals.length] = val;
			} else {
				valArray = new String[1];
				valArray[0] = val;
			}
			ht.put(key, valArray);
		}
		return ht;
	}
}

